package com.googlecode.contests_repo.servlets;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.googlecode.contests_repo.core.config.ConfigurationManager;
import com.googlecode.contests_repo.core.users.AccessRight;
import com.googlecode.contests_repo.core.users.UserManager;

/**
 * Servlet for deleting a given file or folder from the repository.
 */
@WebServlet("/delete_file")
public class DeleteFileServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// String resourcePath = URLDecoder.decode(request.getParameter("path"),
		// "UTF-8");
		String resourcePath = request.getParameter("path");
		String repoRoot = ConfigurationManager.getInstance().getRepoRoot();
		File file = new File(repoRoot + File.separator + resourcePath);
		File parentFile = file.getParentFile();

		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("username");
		if (userName != null
				&& UserManager.hasAccessRight(userName, file.getAbsolutePath(),
						AccessRight.VIEW_FULL)) {
			// boolean success = deleteRecursive(file);
			deleteRecursive(file);

			/*
			 * response.sendRedirect("view_folder.jsp?path=" +
			 * parentFile.getPath().substring(repoRoot.length()) +
			 * "&deleteSuccessful=" + success);
			 */
		}
		response.sendRedirect("resource.jsp?path="
				+ parentFile.getPath().substring(repoRoot.length() + 1)
				+ "&edit=1");
	}

	private boolean deleteRecursive(File file) {
		if (file.isDirectory()) {
			for (File child : file.listFiles()) {
				boolean success = deleteRecursive(child);
				if (!success) {
					return false;
				}
			}
		}

		return file.delete();
	}
}
